﻿using RBAC_Application.Repository.Interface;
using RBAC_Model;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RBAC_Application.Repository.Implement
{
    public class UserRepository : IUserRepository
    {
        private readonly ISqlSugarClient _db;

        public UserRepository(ISqlSugarClient db)
        {
            _db = db;
        }

        /// <summary>
        /// 根据用户ID获取用户信息
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <returns>用户实体</returns>
        public User GetById(long id)
        {
            return _db.Queryable<User>().First(u => u.Id == id && !u.IsDeleted);
        }

        /// <summary>
        /// 根据用户名获取用户信息
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <returns>用户实体</returns>
        public User GetByUserName(string userName)
        {
            return _db.Queryable<User>().Where(u => u.UserName == userName && !u.IsDeleted).First();
        }

        /// <summary>
        /// 获取所有用户信息
        /// </summary>
        /// <returns>用户列表</returns>
        public List<User> GetAll()
        {
            return _db.Queryable<User>().Where(u => !u.IsDeleted).ToList();
        }

        /// <summary>
        /// 根据条件获取用户列表
        /// </summary>
        /// <param name="keyword">关键字（用户名或邮箱）</param>
        /// <param name="isActive">是否激活</param>
        /// <returns>用户列表</returns>
        public List<User> GetByCondition(string keyword, bool? isActive)
        {
            var query = _db.Queryable<User>().Where(u => !u.IsDeleted);
            
            if (!string.IsNullOrEmpty(keyword))
            {
                query = query.Where(u => u.UserName.Contains(keyword) || u.Email.Contains(keyword));
            }
            
            if (isActive.HasValue)
            {
                query = query.Where(u => u.IsActive == isActive.Value);
            }
            
            return query.ToList();
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="user">用户实体</param>
        public void Add(User user)
        {
            _db.Insertable(user).ExecuteCommand();
        }

        /// <summary>
        /// 更新用户
        /// </summary>
        /// <param name="user">用户实体</param>
        public void Update(User user)
        {
            _db.Updateable(user).ExecuteCommand();
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id">用户ID</param>
        public void DeleteUser(long id)
        {
            _db.Ado.BeginTran();
            try
            {
                var user = _db.Queryable<User>().First(u => u.Id == id && !u.IsDeleted);
                if (user == null)
                    throw new InvalidOperationException("用户不存在");

                // 软删除用户-角色关联
                _db.Updateable<UserRole>()
                    .SetColumns(ur => ur.IsDeleted == true)
                    .Where(ur => ur.UserId == id && !ur.IsDeleted)
                    .ExecuteCommand();

                // 软删除用户
                user.IsDeleted = true;
                _db.Updateable(user).ExecuteCommand();

                _db.Ado.CommitTran();
            }
            catch
            {
                _db.Ado.RollbackTran();
                throw;
            }
        }

        /// <summary>
        /// 检查用户名是否已存在
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <returns>是否存在</returns>
        public bool Exists(string userName)
        {
            return _db.Queryable<User>().Any(u => u.UserName == userName && !u.IsDeleted);
        }

      
    }
}
